var Plan = {};

Plan.LimitOption = {
    $form : $('#formEdit'),
    defaultOptVal : 0,  //默认选项
    init : function(){
        var $form = this.$form,
            that = this;
            t = setInterval(function(){ //此处定时检测，主要是为了在表单数据填充完整后再执行以下操作
                if($form.find('[name=planname]').val().length < 1) {
                    return false;
                }

                that.timeLimit();
                that.weekDayLimit();
                that.siteTypeLimit();
                that.siterLimitList();
                that.addSiterLimit();
                that.costLimitList();

                clearInterval(t);
            }, 100);
    },

    timeLimit : function(){
        var $opt = this.$form.find('[name=time_limit]'),
            $checked = $opt.filter(':checked');
            
        $opt.click(function(){
            var s = $(this).val(),
                action = s == -1 ? 'hide' : 'show';

            $('#timeLimitList')[action]();
        })

        if($checked.length < 1) {
            $checked = $opt.filter('[value=' + this.defaultOptVal + ']');
        }

        $checked.trigger('click');
    },

    weekDayLimit : function() {
        var $opt = this.$form.find('[name=week_day_limit]'),
            $checked = $opt.filter(":checked");

        $opt.click(function(){
            var s = $(this).val(),
                action = s == -1 ? 'hide' : 'show';

            $('#weekDayLimitList')[action]();
        })

        if(!$checked.length) {
            $checked = $opt.filter('[value=' + this.defaultOptVal + ']');
        }

        $checked.trigger('click');
    },

    siteTypeLimit : function() {
        var $opt = this.$form.find('[name=site_type_limit]'),
            $checked = $opt.filter(':checked');

        $opt.click(function(){
            var s = $(this).val(),
                action = s == -1 ? 'hide' : 'show';

            $('#siteTypeLimitList')[action]();
        })

        if(!$checked.length) {
            $checked = $opt.filter('[value=' + this.defaultOptVal + ']');
        }

        $checked.trigger('click');
    },

    siterLimitList : function() {
        var dao = Conf.get('planLimitSiter'),
            $o = $('#siterLimitListContainer');

        if(!dao) {
            return false;
        }

        var date = new Date,
            today = [date.getFullYear(), date.getMonth()+1, date.getDate()].join('-');

        $o.html(template('tSiterLimitListTpl', {day : today, uids : dao}));
    },

    /**
     * 计费限制
     */
    costLimitList : function() {
        var $opt = this.$form.find('[name=cost_limit]'),
            $checked = $opt.filter(':checked');

        $opt.click(function() {
            var s = parseInt($(this).val(), 10),
                act = s == 1 ? 'show' : 'hide';

            $('#costLimitList')[act]();
        });

        if (!$checked.length) {
            $checked = $opt.filter('[value=0]');
        }

        $checked.trigger('click');
    },

    /**
     * 增加被限制的站长编号
     */
    addSiterLimit : function() {
        var $o = $('#input_siter_id'),
            $btn = $('#btn_input_siter_id'),
            spliter = [',', '，', '、'],
            spliter2 = '|',
            _this = this;

        $btn.on('click',function() {
            var val = $.trim($o.val());

            if(val.length < 2) {
                alert('请输入需要限制投放的站长UID');
            }

            for(var i = 0, len = spliter.length; i < len; i++) {
                val = val.replace(new RegExp(spliter[i], 'g'), spliter2);
            }

            var tmpIds = val.split(spliter2),
                ids = Conf.get('planLimitSiter') || [],
                r = ids.concat(tmpIds);

            $o.val('');

            if(!r) {
                return false;
            }

            Conf.set('planLimitSiter', r);

            _this.siterLimitList();
        })
    }
}


var Ad = {
    getTypeCn : function(type) {
        var conf = Conf.get('AD_TYPE'),
            r = '未知';

        $.each(conf, function(k, v){
            if(k == type) {
                r = v;
                return false;
            }
        })

        return r;
    },

    getStatusCn : function(status) {
        var conf = Conf.get('AD_STATUS'),
            r = '未知';

        $.each(conf, function(k, v){
            if(k == status) {
                r = v;

                return false;
            }
        })

        return r;
    }
};

Ad.index = {
    init : function() {
        var $d = $(document),
            that = this;

        $d.on('click', '[action=playAd]', function() {
            that.play();
        })

        $d.on('click', '[action=lockAd]', function() {
            that.lock();
        })
    },

    play : function() {
        var url = '?c=Ad&a=doPlay',
            $checkboxItem = $('#zoneBodyContent').find(':checkbox[t=checkboxChoiceItemDom]:checked');

        if($checkboxItem.length < 1) {
            alert('请选择需要开启的广告');

            return false;
        }

        var progress = $.messager.progress,
            dao = [];

        $checkboxItem.each(function(k, v){
            dao.push($(v).val());
        })

        progress({text : '正在开启广告，请稍等...'});

        $.post(url, {id : dao}, function(j){
            progress('close');

            if(!j.s) {
                alert(j.m);

                return false;
            }

            reload();
        }, 'json')
    },

    lock : function() {
        var url = '?c=Ad&a=doLock',
            $checkboxItem = $('#zoneBodyContent').find(':checkbox[t=checkboxChoiceItemDom]:checked');

        if($checkboxItem.length < 1) {
            alert('请选择需要锁定的广告');

            return false;
        }

        var progress = $.messager.progress,
            dao = [];

        $checkboxItem.each(function(k, v){
            dao.push($(v).val());
        })

        progress({text : '正在锁定广告，请稍等...'});

        $.post(url, {id : dao}, function(j){
            progress('close');

            if(!j.s) {
                alert(j.m);

                return false;
            }

            reload();
        }, 'json')
    }
};

Ad.edit = {
    $form : $('#formEdit'),
    init : function() {
        var $form = this.$form,
            that = this;
            t = setInterval(function(){ //此处定时检测，主要是为了在表单数据填充完整后再执行以下操作
                if($form.find('[name=plan_name]').html().length < 1) {
                    return false;
                }

                $form.find('tr[rel]').hide();
                that.ev();

                clearInterval(t);
            }, 100);
    }, 
    ev : function() {
        var that = this,
            $type = this.$form.find('select[name=type]');

        $type.change(function() {
            var type = $(this).val();
            that[type]();
        });

        $type.trigger('change');
    },
    tw : function() {
        var $form = this.$form;

        $form.find('tr[rel]').hide();
        $form.find('tr[rel=size]').show();
        $form.find('tr[rel=html_code]').show();
    },
    zn_tw : function() {
        var $form = this.$form;

        $form.find('tr[rel]').hide();
        $form.find('tr[rel=size]').show();
        $form.find('tr[rel=html_code]').show();
    },
    zn_text : function() {
        var $form = this.$form;

        $form.find('tr[rel]').hide();
        $form.find('tr[rel=size]').show();
        $form.find('tr[rel=html_code]').show();
    },
    img : function() {
        var $form = this.$form;

        $form.find('tr[rel]').hide();
        $form.find('tr[rel=size]').show();
        $form.find('tr[rel=img_url]').show();
    },
    n_zn : function() {
        this.zn_tw();
    },
    dl : function() {
        this.img();
    },
    pf : function() {
        this.img();
    },
    tt : function() {
        this.cpm();
    },
    xn : function() {
        this.cpm();
    },
    cpm : function() {
        var $form = this.$form;

        $form.find('tr[rel]').hide();
        $form.find('tr[rel=cpm_size]').show();

        var $cpmSize = $form.find('[name=cpm_size]');

        $cpmSize.unbind('click').click(function(){
            var action = $(this).val() == 1 ? 'show' : 'hide';
            $form.find('tr[rel=size]')[action]();
        });

        $cpmSize.filter(':checked').trigger('click');
    }
}

var Zone = {};

Zone.edit = {
    $form : $('#formEdit'),
    init : function() {
        var $form = this.$form,
            that = this;
            t = setInterval(function(){ //此处定时检测，主要是为了在表单数据填充完整后再执行以下操作
                if($form.find('[name=zone_name]').val().length < 1) {
                    return false;
                }

                var r = Conf.get('formEditDao'),
                    planType = r.plan_type.toLowerCase();

                that[planType]();
                that.ev();

                clearInterval(t);
            }, 100);
    },

    ev : function() {
        var $form = this.$form,
            $autoView = $form.find('[name=zone_auto_view]'),
            $checked = $autoView.filter(':checked');

        $autoView.click(function(){
            var action = $(this).val() == '1' ? 'hide' : 'show';
            $form.find('#zoneAdList')[action]();
        });

        if($checked.length < 1) {
            $checked = $autoView.filter('[value=1]');
        }

        $checked.trigger('click');
    },

    cpm : function() {
        var $form = this.$form,
            $opt = $form.find('[name=cpm_opt]'),
            $checked = $opt.filter(':checked');

        $form.find('#cpmOptList').show();

        $opt.click(function(){
            var action = $(this).val() == '1' ? 'show' : 'hide';

            $form.find('#cpmOptInterval')[action]();
        });

        if($checked.length < 1) {
            $checked = $opt.filter('[value=0]');
        }

        $checked.trigger('click');
    },

    cpc : function() {
        this.$form.find('#cpmOptList').hide();
    },

    cpv : function() {
        this.cpc();
    }
};


var Site = {};

/**
 * 返回站点状态中文名称
 */
Site.getStatusCn = function(s) {
    s = parseInt(s, 10);

    var cn = Conf.get('SITE_STATUS'),
        r = typeof(cn[s]) == 'undefined' ? '未知' : cn[s];

    return r;
}

var SiteDomain = {};

SiteDomain.edit = {
    init : function() {
        this.ev();
    },

    ev : function() {
        var that = this,
            $siteDomainList = $('.siteDomainList'),
            $o = $siteDomainList.find('li'),
            $addForm = $('.addDomainForm');

        $o.live({
            mouseenter: function() {
                that.showMenu($(this));
            }, 
            click : function() {
                that.showMenu($(this));
            },
            mouseleave: function() {
                that.removeMenu($(this));
            }
        });

        /**
         * 绑定网址状态改变事件
         */
        $o.on('SiteDomain.changeStatus', function(e, m){
            $tmpO = $(this);
            $tmpO.find('span.domainName > b').html('[' + Site.getStatusCn($tmpO.attr('status')) + ']');
        })

        $o.live('eSiteDomainUpdate', function(e, d) {
            var domain = $(this).attr('domain'),
                status = $(this).attr('status'),
                html = '<span class="domainName">[' + Site.getStatusCn(status) + '] '
                       + '<a href="' + Conf.get('REDIRECT_APP') + '?url=' + domain + '" target="_blank">' + domain + '</span>';

            $(this).html(html);
        });

        if($addForm.length > 0) {
            $addForm.find('.btnAddDomain').click(function() {
                that.checkDomainExists($addForm.find('[name=new_domain]').val());
            });

            $addForm.bind('CHECK_DOMAIN_EXISTS_OK', function() {
                var siteId = parseInt($('input[name=site_id]').val(), 10);
                siteId = isNaN(siteId) || !siteId ? null : siteId;

                that.saveAddDomain($addForm, siteId);
            });

            $addForm.bind('CHECK_DOMAIN_EXISTS_ERROR', function(e, m) {
                alert(m.m);
            });

            $addForm.find('.btnCleanAddDomain').click(function() {
                that.cleanAddDomainForm($addForm);
            });
        }

        /**
         * 此绑定的事件为增加新域名
         */
        $('.siteDomainList').bind('eSiteDomainAppend', function(e, d){
            var html = '<li sdid='+ d.id +' domain='+ d.domain +' status=' + d.status + '><span class="domainName"><b>[' + Site.getStatusCn(d.status) + ']</b> '
                   + '<a href="' + Conf.get('REDIRECT_APP') + '?url=' + d.domain + '" target="_blank">' + d.domain + '</span></li>';

            $(this).prepend(html);
        });

    },

    showMenu : function($parent) {
        var status = $parent.attr('status'),
            html = ['<div class="domainMenu">'];

        switch(status) {
            case '0' :  //处于待审状态时，可以审核、拒绝
                html.push(' <a href="javascript:;" t="audit">审核</a> ');
                html.push(' <a href="javascript:;" t="lock">拒绝</a> ');
                break;

            case '1' : //处于拒绝状态时，只有管理员可以审核
            case '2' : //处于锁定状态时，只有管理员可以审核
                if(Conf.get('CURRENT_USER_TYPE') == Conf.get('ADMIN_USER_TYPE')) {
                    html.push(' <a href="javascript:;" t="audit">审核</a> ');
                }
                break;
            case '3' : //处于审核状态时，可以拒绝
                html.push(' <a href="javascript:;" t="lock2">锁定</a> ');
                break;
        }

        /**
         * 只有管理员可以编辑、删除
         */
        if(Conf.get('CURRENT_USER_TYPE') == Conf.get('ADMIN_USER_TYPE')) {
            html.push(' <a href="javascript:;" t="modify">编辑</a> ');
            html.push('<a href="javascript:;" t="del">删除</a> ');
        }

        html.push('</div>');

        var $html = $(html.join(' ')),
            that = this;

        $html.width($parent.width());
        $parent.append($html);
        $parent.addClass('hover');

        $html.find('[t=modify]').click(function(){
            that.showEditForm($parent);
        });

        $html.on('click', '[t=audit],[t=lock],[t=lock2]', function(e) {
            var $o = $(e.target),
                action = $o.attr('t'),
                actionConf = {
                    lock  : 1, //拒绝
                    lock2 : 2, //锁定
                    audit : 3  //审核
                };

            if(typeof(actionConf[action]) == 'undefined') {
                alert('操作类型有误');
            }

            var status = actionConf[action],
                id = parseInt($parent.attr('sdid'), 10),
                progress = $.messager.progress;

            progress({text : '正在提交数据，请稍等...'});

            $(window).on('SiteDomain.changeStatusAction', function(e, m){
                progress('close');

                if(!m.s) {
                    alert(m.m);
                }

                $parent.attr('status', status);
                $parent.trigger('SiteDomain.changeStatus');
                that.removeMenu($parent);
            });

            that.changeStatus(id, status);
        })

        $html.find('[t=del]').click(function(){
            that.delDomain($parent);
            that.removeMenu($parent);
        });


        return $html;
    },

    removeMenu : function($parent) {
        $parent.find('.domainMenu').remove();
        $parent.removeClass('hover');
    },

    showEditForm : function($parent) {
        var html = $('#tEditDomain').html(),
            $html = $(html),
            that = this,
            domain = $parent.attr('domain'),
            status = $parent.attr('status'),
            $status = $html.find('[name=status]');

        $html.find('[name=domain]').val(domain);
        $html.find('[name=status][value=' + status + ']').attr('checked', true);

        switch(status) {
            case '0' :  //处于待审状态时，可以待审、审核、拒绝
                $status.filter('[value=2]').parent().remove();
                break;

            case '2' : //处于锁定状态时，可以审核、锁定
            case '3' : //处于审核状态时，可以审核、锁定
                $status.filter('[value=0]').parent().remove();
                $status.filter('[value=1]').parent().remove();
                break;

            case '1' : //处于拒绝状态时，可以审核、拒绝
                $status.filter('[value=0]').parent().remove();
                $status.filter('[value=2]').parent().remove();
                break;
        }

        $html.find('button.tBtnSave').click(function(){
            that.saveDomain($html, $parent);
            that.removeEditForm($parent);
        });

        $html.find('button.tBtnClose').click(function(){
            that.removeEditForm($parent);
        });

        $parent.html($html);
    }, 

    /**
     * 保存域名编辑后的信息
     */
    saveDomain : function($form, $parent) {
        var domain = $form.find('[name=domain]').val(),
            status = $form.find('[name=status]:checked').val(),
            sdid = parseInt($parent.attr('sdid'), 10);

        /**
         * 如果sdid小于1，说明没有真正的编号，这种情况只存在于新增网站时
         */
        if(sdid < 1) {
            $parent.attr('domain', domain).attr('status', status);
            $parent.trigger('eSiteDomainUpdate');

            return true;
        }

        var url = '?c=SiteDomain&a=doSave&id=' + $parent.attr('sdid') + '&domain=' + domain + '&status=' + status;

        $.getJSON(url, function(j){
            if(!j.s) {
                alert(j.m);
            } else {
                $parent.attr('domain', domain).attr('status', status);
            }

            $parent.trigger('eSiteDomainUpdate');
        })
    },

    /**
     * 改变域名状态
     */
    changeStatus : function(id, status) {
        var url = '?c=SiteDomain&a=doChangeStatus';

        $.getJSON(url, {id : id, status : status}, function(j) {
            $(window).trigger('SiteDomain.changeStatusAction', j);
        });
    },

    /**
     * 返回增加网站时登记的域名，这部分域名跟随网站一起保存
     * 此方法只适用于增加新网站时
     */
    getAddDomainDao : function() {
        var $listItem = $('.siteDomainList li');

        if($listItem.length < 1) {
            return false;
        }

        var r = [];

        $.each($listItem, function(k, v){
            var $o = $(v);
            r.push({id : $o.attr('sdid'), domain : $o.attr('domain'), status : $o.attr('status')});
        })

        return r;
    },

    setAddDomainDao : function(dao) {
        var $dao = $('#formEdit').find('[name=domain_dao]'),
            s = [];
        
        $.each(dao, function(k, v) {
            s.push(v.domain + ',' + v.status);
        })

        $dao.val(s.join('|'));
    },

    /**
     * 保存新增的域名
     * 如果无siteId参数，则把增加的域名保存至site_domain这个hidden表单项目中
     */
    saveAddDomain : function($form, siteId) {
        var domain = $form.find('[name=new_domain]').val(),
            status = $form.find('[name=new_status]:checked').val(),
            url = '?c=SiteDomain&a=doAdd',  //此API成功后返回新增的数据行
            dao = {domain : domain, status : status},
            that = this,
            $domain = $form.find('[name=domain]');

        siteId = typeof(siteId) == 'undefined' ? 0 : parseInt(siteId, 10);

        /**
         * 无网站编号说明是新增网站，所以登记的域名不能直接保存至服务器，先存至表单
         */
        if(!siteId) {
            var domainDao = this.getAddDomainDao() || [],
                exists = 0;

            $.each(domainDao, function(k, v) {
                if(v.domain == domain) {
                    exists = 1;
                    alert('域名已经存在');

                    return false;
                }
            })

            if(exists) {
                return true;
            }

            var tmp = {id : 0, domain : domain, status : status};
            domainDao.push(tmp);
            this.setAddDomainDao(domainDao);

            $('.siteDomainList').trigger('eSiteDomainAppend', tmp);
            this.cleanAddDomainForm($form);

            return true;
        }

        dao.site_id = siteId;

        $.getJSON(url, dao, function(j) {
            if(!j.s) {
                alert(j.m);
            } else {
                var d = j.d;
                $('.siteDomainList').trigger('eSiteDomainAppend', {id : d.id, domain : d.domain, status : d.status});
                that.cleanAddDomainForm($form);
            }
        });
    },

    /**
     * 清空增加域名的表单
     */
    cleanAddDomainForm : function($form) {
        $form.find('[name=new_domain]').val('');
        $form.find('[name=new_status][value=0]').attr('checked', true);
    },

    /**
     * 检测域名是否存在
     */
    checkDomainExists : function(domain, sdid) {
        if(typeof(domain) != 'string') {
            alert('请指定待检测的域名');

            return false;
        }

        if(domain.length < 1) {
            alert('请输入域名');

            return false;
        }

        var url = '?c=SiteDomain&a=checkDomainExists',
            dao = {domain : domain};

        if(typeof(sdid) != 'undefined') {
            dao = {id : sdid};
        }

        $.getJSON(url, dao, function(j) {
            if(j.s) {
                $('.addDomainForm').trigger('CHECK_DOMAIN_EXISTS_ERROR', {m : j.m});
            } else {
                $('.addDomainForm').trigger('CHECK_DOMAIN_EXISTS_OK');
            }
        });
    },

    delDomain : function($parent) {
        if(!confirm('确认删除域名[' + $parent.attr('domain') + ']吗？')) {
            return false;
        }

        var sdid = parseInt($parent.attr('sdid'), 10);

        if(sdid < 1) {
            $parent.remove();

            return true;
        }

        var url = '?c=SiteDomain&a=del&id=' + sdid;

        $.getJSON(url, function(j) {
            if(!j.s) {
                alert(j.m);
            } else {
                $parent.remove();
            }
        })
    },

    removeEditForm : function($parent) {
        $parent.find('.domainEditForm').remove();
        this.removeMenu($parent);
        $parent.trigger('eSiteDomainUpdate');
    }
};

var PayLog = {};

PayLog.index = {
    init : function() {
        this.ev();
    },
    ev : function() {
        var $payLogForm = $('#payLogListForm'),
            $mPayBtn = $('#mPayBtn'),
            $scale = $('tr input[t=scale]', $payLogForm),
            $payMoney = $('tr input[t=payMoney]', $payLogForm),
            $comment = $('tr textarea[t=comment]', $payLogForm),
            $saveLink = $('tr a[action=save]', $payLogForm),    //保存链接
            $payLink = $('tr a[action=pay]', $payLogForm), //支付链接
            $unPayLink = $('tr a[action=unPay]', $payLogForm),  //撤消支付链接
            that = this;

        $(window).on('CHANGED_SF_MONEY', function() {
            that.sumSfMoney.call(that);
        })

        $mPayBtn.click(function() {
            var $form = $('#payLogListForm'),
                $id = $form.find('td input[name=id\[\]]:checked'),
                choiceCount = $id.length,    //已选中的项目数
                canPayCount = 0,    //可以支付的项目数
                okPayCount = 0, //成功支付的项目数
                errorPayCount = 0,  //支付出错的项目数
                $canPayParent = []; //可以支付数据对象的父节点对象

            if(choiceCount < 1) {
                alert('请选择需要支付的项目');

                return false;
            }

            $.each($id, function(k, v){
                var $o = $(v),
                    $parent = $o.parents('tr'),
                    $scale = $parent.find('input[t=scale]');

                if($scale.attr('status') == '0') {
                    $canPayParent.push($parent);
                    canPayCount++;
                }
            })

            if(canPayCount < 1) {
                alert('选择的项目已经支付过');

                return false;
            }

            $.each($canPayParent, function(k, v){
                var $parent = v,
                    dao = that.getDao($parent),
                    id = dao.id,
                    cEvent = 'PAY_LOG_SAVE_OK.M_PAY_BTN_' + id;

                $(window).bind(cEvent, function(e, d){
                    that.hideSaveAction($parent);
                    $parent.find('a[action=pay]').hide();
                    $parent.find('a[action=unPay]').show();
                    $parent.find('td').eq(3).html('已支付');
                    $parent.find('input[t=scale]').attr('status', 1);
                    $(this).unbind(cEvent);

                    okPayCount++;

                    if(okPayCount == canPayCount) {
                        alert('选中项目已支付完毕');
                        reload();
                    }
                })

                dao.status = 1;
                that.save(dao);
            })
        });

        /**
         * 实时输入实付比例
         */
        $scale.on('input', function() {
            var scale = parseInt($(this).val(), 10),
                money = $(this).attr('money'),
                $parent = $(this).parents('tr');

            scale = isNaN(scale) ? 0 : scale;

            var payMoney = money * scale;
            payMoney = String(payMoney).split('.')[0];
            payMoney = payMoney / 100;

            $payMoney = $parent.find('input[t=payMoney]').val(payMoney);

            that.showSaveAction($parent);
            $(window).trigger('CHANGED_SF_MONEY');
        })

        /**
         * 实时输入实付金额
         */
        $payMoney.on('input', function() {
            var $parent = $(this).parents('tr');

            that.showSaveAction($parent);
            $(window).trigger('CHANGED_SF_MONEY');
        })

        /**
         * 实时输入备注
         */
        $comment.on('input', function() {
            var $parent = $(this).parents('tr');

            that.showSaveAction($parent);
        })

        /**
         * 保存操作
         */
        $saveLink.click(function() {
            var $parent = $(this).parents('tr'),
                dao = that.getDao($parent),
                id = dao.id,
                cEvent = 'PAY_LOG_SAVE_OK.SAVE_LINK_' + id;

            $(window).bind(cEvent, function(e, d) {
                  that.hideSaveAction($parent);
                  $(this).unbind(cEvent);
            });

            that.save(dao);
        })

        /**
         * 支付操作
         */
        $payLink.click(function() {
            var $parent = $(this).parents('tr'),
                dao = that.getDao($parent),
                id = dao.id,
                $o = $(this),
                cEvent = 'PAY_LOG_SAVE_OK.PAY_LINK_' + id;

            $(window).bind(cEvent, function(e, d){
                  $o.hide();
                  $parent.find('td').eq(3).html('已支付');
                  $(this).unbind(cEvent);
                  $parent.find('a[action=unPay]').show();
                  $parent.find('input[t=scale]').attr('status', 1);
            })

            dao.status = 1;
            that.save(dao);
        })

        /**
         * 撤消支付操作
         */
        $unPayLink.click(function(){
            var $parent = $(this).parents('tr'),
                dao = that.getDao($parent),
                id = dao.id,
                $o = $(this),
                cEvent = 'PAY_LOG_SAVE_OK.UN_PAY_LINK_' + id;

            $(window).bind(cEvent, function(e, d){
                  $o.hide();
                  $parent.find('td').eq(3).html('待支付');
                  $parent.find('a[action=pay]').show();
                  $parent.find('input[t=scale]').attr('status', 0);
                  $(this).unbind(cEvent);
                  reload();
            })

            dao.status = 0;
            that.save(dao);
        })

    },

    /**
     * 汇总当页实付金额
     */
    sumSfMoney : function() {
        var $form = $('#payLogListForm'),
            $payMoney = $form.find('[t=payMoney]'),
            $sfMoneyZone = $('#sf_money_zone'),
            money = 0;

        if ($payMoney.length > 0) {
            $.each($payMoney, function(k, v) {
                money += parseInt($(v).val() * 100, 10);
            })
        }

        money = money / 100;

        $sfMoneyZone.html(money);
    },

    /**
     * 获取每行的可编辑数据
     */
    getDao : function($parent) {
        var $input = $parent.find('input');

        return { 
                    id : $input.eq(0).val(),
                    scale : $input.eq(1).val(),
                    pay_money : $input.eq(2).val(),
                    comment : $parent.find('textarea').val()
                };
    },

    /**
     * 显示“保存” 操作
     */
    showSaveAction : function($parent) {
        var $action = $parent.find('a[action=save]');

        if($action.is(':hidden')) {
            $action.show();
        }
    },

    /**
     * 隐藏“保存”操作
     */
    hideSaveAction : function($parent) {
        var $action = $parent.find('a[action=save]');

        if($action.not(':hidden')) {
            $action.hide();
        }
    },

    /**
     * 保存单行支付数据
     */
    save : function(dao) {
        var url = '?c=PayLog&a=doSave';

        $.post(url, dao, function(j) { 
            var msg = 'PAY_LOG_SAVE_OK';

            if(!j.s) {
                alert(j.m);
                msg = 'PAY_LOG_SAVE_ERROR';
            }

            $(window).trigger(msg, {id : dao.id});
        }, 'json');
    }

};

var Recharge = {};

Recharge.edit = {
    cEventSaveOk : 'RECHARGE_SAVE_OK',
    cEventSaveError : 'RECHAGE_SAVE_ERROR',

    init : function() {
        var that = this;

        $('a[action=deduction]').click(function() {
            that.deduction($(this).attr('data'));
        });
    },

    add : function(userName, moneyField) {
        var $rechargeEditForm = $('#tRechargeEditForm'),
            $form = $rechargeEditForm,
            that = this,
            $userName = $('input[name=user_name]', $form);

        //清除表单中残留数据
        $userName.val('');
        $('input[name=r_money]', $form).val('');
        $('textarea[name=r_comment]', $form).val('');

        $rechargeEditForm.dialog({
            title : '手工充值',
            width : 400,
            height : 300,
            modal : true,
            buttons : [
                {text: '保存', handler : function() {
                    var $form = $rechargeEditForm,
                        dao = {
                            user_name : $('input[name=user_name]', $form).val(),
                            r_status  : $('input[name=r_status]:checked', $form).val(),
                            r_money   : $('input[name=r_money]', $form).val(),
                            r_comment : $('textarea[name=r_comment]', $form).val()
                        };

                    if($rechargeEditForm.find('dd[t=moneyType]').is(':visible')) {
                        dao.r_money_type = $rechargeEditForm.find('input[name=r_money_type]:checked').val();
                    }

                    var $o = $(window);

                    $o.bind(that.cEventSaveOk + '.' + dao.user_name, function(e, msg){
                        $rechargeEditForm.dialog('close');
                        reload();
                    });

                    $o.bind(that.cEventSaveError + '.' + dao.user_name, function(e, msg){
                        alert(msg);

                        return false;
                    });

                    that.save(dao);
                }},
                {text: '关闭', handler : function() {$rechargeEditForm.dialog('close');}}
            ]
        });

        var timer;

        $userName.off('input').on('input', function() {
            var $that = $(this),
                cOkEvent = 'USER_GET_BY_USER_NAME_OK.',
                cErrorEvent = 'USER_GET_BY_USER_NAME_ERROR.',
                name = '';

            $('[t=moneyType]', $rechargeEditForm).hide();
            clearTimeout(timer);

            timer = setTimeout(function(){
                name = $that.val();

                if(name.length < 1) {
                    return false;
                }

                $(window).one(cOkEvent + name, function(e, msg){
                    var action = msg.type == 1 ? 'show' : 'hide',
                        $moneyType = $('[t=moneyType]', $rechargeEditForm);

                    $moneyType[action]();

                    /**
                     * 只有广告主才能预充
                     */
                    var $rStatus5Parent = $('input[name=r_status][value=5]', $rechargeEditForm).parent();
                    action = msg.type == 2 ? 'show' : 'hide';
                    $rStatus5Parent[action]();
                });

                $(window).one(cErrorEvent + name, function(e, msg){
                    var $o = $that.parent().find('span');
                    $o.html(msg);

                    setTimeout(function(){
                        $o.html('');
                    }, 1000);
                });

                try {
                    that.getByUserName(name);
                } catch(ex) {
                    alert(ex);
                }
            }, 500);
        })

        if(typeof(userName) == 'string') {
            $userName.val(userName).trigger('input');
        }

        if(typeof(moneyField) == 'string') {
            $('input[name=r_money_type][value=' + moneyField + ']', $form).attr('checked', true);
        }
    },

    getByUserName : function(userName) {
        if(userName.length < 1) {
           throw '请输入会员名称';
        }

        var url = '?c=User&a=getByUserName',
            cEvent = 'USER_GET_BY_USER_NAME_OK.' + userName,
            cErrorEvent = 'USER_GET_BY_USER_NAME_ERROR.' + userName;

        $.getJSON(url, {name:userName}, function(j){
            var msg, ev;

            if(j.s) {
                msg = j.d;
                ev = cEvent;
            } else {
                msg = j.m;
                ev = cErrorEvent;
            }

            $(window).trigger(ev, msg);
        })
    },

    save : function(dao) {
        var url = '?c=Recharge&a=doSave',
            that = this;

        $.post(url, dao, function(j){
            var msg = j.m,
                ev = j.s ? that.cEventSaveOk : that.cEventSaveError;
            
            ev += '.' + dao.user_name;

            $(window).trigger(ev, msg);
        }, 'json');
    },

    getById : function(id) {
        var url = '?c=Recharge&a=getById';

        $.getJSON(url, {id : id}, function(j) {
            if(!j.s) {
                alert(j.m);

                return false;
            }

            $(window).trigger('RECHARGE_GET_BY_ID_OK.'+id, j.d);
        })
    },

    /**
     * 扣除
     */
    deduction : function(id) {  
        var progress = $.messager.progress,
            that = this;
        
        progress({
            text : '正在载入数据，请稍等...'
        });

        $(window).one('RECHARGE_GET_BY_ID_OK.'+id, function(e, d){
            progress('close');
            that.showDeductionDialog(d);
        })

        this.getById(id);
    },

    showDeductionDialog : function(dao) {
        var $dialog = $('#tRechargeEditForm'),
            that = this;

        $dialog.dialog({
            title : '手工充值',
            width : 400,
            height : 300,
            modal : true,
            buttons : [
                {text: '保存', handler : function() {
                    var d = {
                            user_name : $('input[name=user_name]', $dialog).val(),
                            r_status  : $('input[name=r_status]:checked', $dialog).val(),
                            r_money   : $('input[name=r_money]', $dialog).val(),
                            r_comment : $('textarea[name=r_comment]', $dialog).val(),
                            r_id      : dao.r_id
                        };

                    var $o = $(window);

                    $o.off('RECHARGE_SAVE_DEDUCTION_OK.' + dao.r_id).bind('RECHARGE_SAVE_DEDUCTION_OK.' + dao.r_id, function(e, msg){
                        $dialog.dialog('close');
                        reload();
                    });

                    $o.off('RECHARGE_SAVE_DEDUCTION_ERROR.' + dao.r_id).bind('RECHARGE_SAVE_DEDUCTION_ERROR.' + dao.r_id, function(e, msg){
                        alert(msg);

                        return false;
                    });

                    that.saveDeduction(d);
                }},
                {text: '关闭', handler : function() {$dialog.dialog('close');}}
            ]
        });

        $input = $('input', $dialog);
        $input.attr('disabled', true);
        $input.filter('[name=user_name]').val(dao.user_name);
        $input.filter('[name=r_status][value=' + 4 + ']').attr('checked', true);
        $input.filter('[name=r_money]').val(dao.r_money);
            
        $('textarea[name=r_comment]', $dialog).val('扣除' + dao.user_name + '于' + dao.r_finish_time + '预充的' + dao.r_money + '元。');
    }, 

    saveDeduction : function(dao) {
        var url = '?c=Recharge&a=doDeduction';

        $.post(url, dao, function(j){
            var ev = j.s ? 'RECHARGE_SAVE_DEDUCTION_OK.' : 'RECHARGE_SAVE_DEDUCTION_ERROR.';
                msg = j.m;

            ev += dao.r_id;

            $(window).trigger(ev, msg);
        }, 'json');
    }
};

var Message = {};

Message.edit = {
    add : function(toUser) {
        var $dialog = $('#tMessageAddForm'),
            that = this,
            toUser = toUser || '';

        $dialog.dialog({
            title : '发送短消息',
            width : 400,
            height : 230,
            modal : true,
            buttons : [
                {text : '发送', handler : function(){
                    var name = $('input[name=m_to_user]', $dialog).val(),
                        msg = $('textarea[name=m_text]', $dialog).val();

                    if(name.legnth < 1) {
                        alert('请输入接收人名称');

                        return false;
                    }

                    if(msg.length < 1) {
                        alert('请输入短消息内容');

                        return false;
                    }

                    $(window).one('MESSAGE_SEND.' + name , function(e, m){
                        if(!m.s) {
                            alert(m.m);

                            return false;
                        }

                        $dialog.dialog('close');
                    });

                    that.send({m_to_user : name, m_text : msg});
                }},
                {text : '关闭', handler : function(){$dialog.dialog('close');}}
            ]
        });

        var $toUser = $('input[name=m_to_user]', $dialog),
            $msgZone = $toUser.parent().find('span'),
            timer;

        $toUser.val('');
        $('textarea[name=m_text]', $dialog).val('');

        $toUser.off('input').on('input', function() {
            var name = $(this).val();

            if(name.length < 1) {
                return false;
            }

            clearTimeout(timer);

            timer = setTimeout(function() {
                $(window).one('MESSAGE_IS_USER_EXISTS.' + name, function(e, m){
                    var action = m ? 'hide' : 'show';
                    $msgZone[action]();
                });

                that.isExistsByUserName(name);
            }, 500);
        })

        if(toUser.length > 0) {
            $toUser.val(toUser).trigger('input');
        }
    },

    isExistsByUserName : function(name) {
        var url = '?c=User&a=isExistsByUserName';

        $.getJSON(url, {user_name : name}, function(j){
            $(window).trigger('MESSAGE_IS_USER_EXISTS.' + name, j.s);
        });
    }, 

    send : function(dao) {
        var url = '?c=Message&a=doSend';

        $.post(url, dao, function(j) {
            $(window).trigger('MESSAGE_SEND.' + dao.m_to_user, j);
        }, 'json');
    }
}

var SiteType = {};

SiteType.edit = {
    init : function() {
        var that = this;

        $('#siteTypeListWrap li').live({
            mouseenter: function() {
                that.showMenu($(this));
            }, 
            mouseleave: function() {
                that.removeMenu($(this));
            }
        });

        $('#siteTypeListWrap dt').live({
            mouseenter: function() {
                that.showMenu($(this));
            }, 
            mouseleave: function() {
                that.removeMenu($(this));
            }
        });


    },

    add : function() {
        var progress = $.messager.progress,
            that = this,
            $dialog = $('#tSiteTypeAddForm');

        progress({text : '正在获取顶级分类数据，请稍等...'});

        $(window).one('SITE_TYPE_GET_TOP_CATE', function(e, m){
            progress('close');

            $dialog.dialog({
                title : '增加网站类型',
                width : 350,
                height : 150,
                modal : true,
                buttons : [
                    {text : '保存', handler : function() {
                        var $pid = $('select[name=pid]', $dialog),
                            $name = $('input[name=name]', $dialog),
                            pid = $pid.val(),
                            name = $name.val();

                        if(name.length < 1) {
                            alert('请输入名称');

                            return false;
                        }

                        progress({text : '正在提交数据，请稍等...'});

                        $(window).one('SITE_TYPE_SAVE', function(e, m){
                            progress('close');

                            if(!m.s){
                                alert(m.m);

                                return false;
                            }

                            $name.val('');
                            that.genTopCate($dialog, pid);
                            $pid.val(pid);    //重新选中前次选中的项目
                        });

                        that.save({pid : pid, name : name});
                    }},
                    {text : '关闭', handler : function() {$dialog.dialog('close');reload();}},
                ]
            });
        });

        this.genTopCate($dialog);
        $('input[name=name]', $dialog).val('');
    },

    genTopCate : function($dialog, pid) {
        var cateHtml = '<option value="0">顶级分类</option>';
        pid = pid || 0;

        $(window).one('SITE_TYPE_GET_TOP_CATE', function(e, m){
            if(m.s) {
                $.each(m.d, function(k, v) {
                    cateHtml += '<option value="' + v.id + '">' + v.name + '</option>';
                })
            }

            $('select[name=pid]', $dialog).html(cateHtml).val(pid);
        });

        this.getTopCate();
    },

    /**
     * 返回顶级分类
     */
    getTopCate : function() {
        var url = '?c=SiteType&a=getByPid';

        $.getJSON(url, function(j){
            $(window).trigger('SITE_TYPE_GET_TOP_CATE', j);
        });
    },

    save : function(dao) {
        var url = '?c=SiteType&a=doSave';

        $.post(url, dao, function(j){
            $(window).trigger('SITE_TYPE_SAVE', j);
        }, 'json');
    },

    showMenu : function($parent) {
        var $menu = $('<div class="siteTypeEditMenu"><a href="javascript:;" action="modify">编辑</a><a href="javascript:;" action="del">删除</a></div>'),
            that = this,
            progress = $.messager.progress;

        $parent.append($menu);

        $menu.find('[action=modify]').click(function() {
            var id = $parent.attr('data'),
                name = $parent.attr('data2'),
                $dialog = $('#tSiteTypeAddForm');

            progress({text : '正在获取分类数据，请稍等...'});

            $(window).on('SITE_TYPE_GET_TOP_CATE', function(e, m){
                progress('close');

                if(!m.s) {
                    alert(m.m);

                    return false;
                }

                $dialog.dialog({
                    title : '编辑网站类型',
                    width : 350,
                    height: 150,
                    modal : true,
                    buttons : [
                        {text : '保存', handler : function() {
                            var pid = $('select[name=pid]', $dialog).val(),
                                name = $('input[name=name]', $dialog).val(),
                                progress = $.messager.progress;

                            if(name.length < 1) {
                                alert('请输入名称');

                                return false;
                            }

                            progress({text : '正在保存，请稍等...'});

                            $(window).one('SITE_TYPE_SAVE', function(e, m){
                                progress('close');

                                if(!m.s) {
                                    alert(m.m);

                                    return false;
                                }

                                reload();
                            });

                            that.save({id : id, pid : pid, name : name});
                        }},
                        {text : '关闭', handler : function(){$dialog.dialog('close');reload();}}
                    ]
                });

                /**
                 * 防止给表单赋值时，select[name=pid]还未生成
                 */
                setTimeout(function() {
                    $('input[name=name]', $dialog).val($parent.attr('data2'));
                    $('select[name=pid]', $dialog).val($parent.attr('data3'));
                }, 500);
            })

            that.genTopCate($dialog);
        });

        $menu.find('[action=del]').click(function(){
            if(!confirm('确认删除吗？')) {
                return false;
            }

            progress({text : '正在删除，请稍等...'});

            var id = $parent.attr('data');

            $(window).on('SITE_TYPE_DEL.' + id, function(e, m){
                progress('close');

                if(!m.s) {
                    alert(m.m);

                    return false;
                }

                reload();
            });

            that.del(id);
        });
    },

    removeMenu : function($parent) {
        var $menu = $parent.find('.siteTypeEditMenu');
        $menu.remove();
    },

    del : function(id) {
        var url = '?c=SiteType&a=del';

        $.getJSON(url, {id : id}, function(j){
            $(window).trigger('SITE_TYPE_DEL.' + id, j);
        });
    }
};

var User = {
    init : function() {
        var that = this,
            $o = $(document);

        $o.on('click', 'a[action=logout]', function() {
            if(!confirm('确认退出系统吗？')) {
                return false;
            }

            that.logout();
        })

        $o.on('click', 'a[action=passwd]', function() {

            that.showPasswd();
        })
    },

    logout : function() {
        var url = '?a=doLogout';

        $.getJSON(url, function(j){
            reload(Conf.get('LOGOUT_TO_URL'));
        })
    },

    showPasswd : function() {
        var $dialog = $('#tPasswd'),
            that = this;

        $dialog.dialog({
            title : '修改密码',
            width : 300,
            height : 180,
            modal : true,
            buttons : [
                {text : '保存', handler : function() {
                    var $oldPasswd = $('[name=old_passwd]', $dialog),
                        $newPasswd = $('[name=new_passwd]', $dialog),
                        $newPasswd2 = $('[name=new_passwd_2]', $dialog),
                        oldPasswd = $oldPasswd.val(),
                        newPasswd = $newPasswd.val(),
                        newPasswd2 = $newPasswd2.val();

                    if(oldPasswd.length < 1) {
                        alert('请输入旧密码');
                        $oldPasswd.focus();

                        return false;
                    }

                    if(newPasswd.length < 1) {
                        alert('请输入新密码');
                        $newPasswd.focus();

                        return false;
                    }

                    if(newPasswd2.length < 1) {
                        alert('请再输入一次新密码');
                        $newPasswd2.focus();

                        return false;
                    }

                    if(oldPasswd == newPasswd) {
                        alert('新密码不能与旧密码相同');
                        $newPasswd.focus();

                        return false;
                    }

                    if(newPasswd != newPasswd2) {
                        alert('两次输入的新密码不一致');
                        $newPasswd.focus();

                        return false;
                    }

                    $(window).on('USER_PASSWD', function(e, d){
                        if(!d.s) {
                            alert(d.m);

                            return false;
                        }

                        $dialog.dialog('close');
                    });

                    that.savePasswd({old_passwd : oldPasswd, new_passwd : newPasswd});
                }},
                {text : '关闭', handler : function() {$dialog.dialog('close');}}
            ]
        });
    },

    savePasswd : function(dao) {
        var url = '?a=doPasswd';

        $.post(url, dao, function(j){
            $(window).trigger('USER_PASSWD', j);
        }, 'json')
    }

};

User.edit = {
    /**
     * 会员类型对应的数据地址
     */
    typeUrl : {
            3 : '?c=SiterService',
            4 : '?c=AderService',
            5 : '?c=Admin'
    },

    init : function() {
        var $d = $(document),
            that = this;

        $d.on('click', '[action=addAderService]', function() {
            that.add(4);
        });

        $d.on('click', '[action=addSiterService]', function() {
            that.add(3);
        });

        $d.on('click', '[action=addAdmin]', function() {
            that.add(5);
        });

        $d.on('click', '[action=modifyUser]', function() {
            var uid = parseInt($(this).attr('data-id'), 10),
                type = parseInt($(this).attr('data-type'), 10),
                progress = $.messager.progress;

            if(isNaN(uid) || uid < 1) {
                alert('参数有误');

                return false;
            }

            progress({text : '正在获取会员信息，请稍等...'});

            $(window).one('User_edit_read', function(e, d) {
                progress('close');

                if(!d.s) {
                    alert(d.m);

                    return false;
                }

                that.modify(d.d);
            });

            that.read(uid, type);
        })

        $d.on('click', '[action=delUser]', function() {
            if(!confirm('确认要删除吗？')) {
                return false;
            }

            var id = parseInt($(this).attr('data-id'), 10),
                type = parseInt($(this).attr('data-type'), 10),
                progress = $.messager.progress;

            if(isNaN(id) || id < 1) {
                alert('参数有误');

                return false;
            }

            progress({text : '正在删除数据，请稍等...'});

            $(window).one('User_edit_del', function(e, d){
                progress('close');

                if(!d.s) {
                    alert(d.m);

                    return false;
                }

                reload();
            });

            that.del(id, type);
        })
    },

    add : function(type) {
        var $o = $('#tUserAddForm').clone(),
            ev = [
                {name : 'user_name', handler : 'checkName'},
                {name : 'contact', handler : 'checkContact'},
                {name : 'password', handler : 'checkPasswd'},
                {name : 'qq', handler : 'checkQq'},
                {name : 'recommend_income_scale'},
                {name : 'status'},
                {name : 'type'}
            ],
            that = this,
            type = typeof(type) != 'undefined' ? parseInt(type, 10) : 3;

        type = isNaN(type) ? 3 : type;

        $o.dialog({
            title : '增加会员',
            modal : true,
            buttons : [
                {text : '保存', handler : function() {
                    $(window).on('User_edit_save', function(e, d){
                        if(!d.s) {
                            alert(d.m);

                            return false;
                        }

                        $('[name=user_name]', $o).val('');
                        $('[name=contact]', $o).val('');
                        $('[name=password]', $o).val('');
                        $('[name=qq]', $o).val('');
                        $('[name=status][value=1]', $o).attr('checked', true);
                    });

                    that.save($o, ev);
                }},
                {text : '关闭', handler : function() { $o.dialog('close'); }}
            ]
        });

        $('[name=type]', $o).click(function(o) {
            var $self = $(o.target),
                type = parseInt($self.val(), 10);

            that.showIncomeScale($o, type);
        });

        $('[name=type][value=' + type + ']', $o).trigger('click');

        $.each(ev, function(k, v){
            if(typeof(v.handler) == 'undefined') {
                return ;
            }

            $o.on('blur', '[name=' + v.name + ']', function() {
                that[v.handler]($(this));
            })
        })
    },

    read : function(id, type) {
        var url = this.typeUrl[type] + '&a=read';

        $.getJSON(url, {id : id}, function(j){
            $(window).trigger('User_edit_read', j);
        });
    },

    modify : function(dao) {
        var $o = $('#tUserModifyForm').clone(),
            ev = [
                {name : 'uid'},
                {name : 'contact', handler : 'checkContact'},
                {name : 'password', handler : 'checkPasswdForModify'},
                {name : 'qq', handler : 'checkQq'},
                {name : 'type'},
                {name : 'recommend_income_scale'},
                {name : 'status'}
            ],
            that = this;

        $('[name=uid]', $o).val(dao.uid);
        $('[name=contact]', $o).val(dao.contact);
        $('[name=qq]', $o).val(dao.qq);
        $('[name=status][value=' + dao.status + ']', $o).attr('checked', true);
        $('[name=user_name]', $o).html(dao.user_name);
        $('[name=recommend_income_scale]', $o).val(dao.recommend_income_scale);

        var $type = $('[name=type]', $o),
            $type2 = $type.filter('[value=' + dao.type + ']');

        $type.click(function(o) {
            var $self = $(o.target),
                type = parseInt($self.val(), 10);

            that.showIncomeScale($o, type);
        });

        $type2.attr('checked', true);
        $type2.trigger('click');

        $o.dialog({
            title : '编辑会员',
            modal : true,
            buttons : [
                {text : '保存', handler : function() {
                    $(window).on('User_edit_save', function(e, d){
                        $o.dialog('close');
                        reload();
                    });

                    that.save($o, ev);
                }},
                {text : '关闭', handler : function() { $o.dialog('close'); }}
            ]
        });

        $.each(ev, function(k, v){
            if(typeof(v.handler) == 'undefined') {
                return ;
            }

            $o.on('blur', '[name=' + v.name + ']', function() {
                that[v.handler]($(this));
            })
        })
    },

    /**
     * 显示或隐藏设置提成比例项目
     */
    showIncomeScale : function($parent, type) {
        var action = type == 5 ? 'hide' : 'show';   //5表示管理员
        $parent.find('[g=income_scale]')[action]();
    },

    del : function(id, type) {
        var url = this.typeUrl[type] + '&a=del';

        $.getJSON(url, {id : id}, function(j){
            $(window).trigger('User_edit_del', j);
        });
    },

    save : function($parent, ev) {
        var errorCounter = 0,
            dao = {},
            that = this;

        $.each(ev, function(k, v){
            var $o = $('[name=' + v.name + ']', $parent),
                domType = $o[0]['type'];

            if(errorCounter < 1) {
                if(domType == 'radio') {
                    dao[v.name] = $o.filter(':checked').val();
                } else {
                    dao[v.name] = $o.val();
                }
            }

            if(typeof(v.handler) == 'undefined') {
                return;
            }

            if(!that[v.handler].call(that, $o)) {
                errorCounter++;
            }
        })

        if(errorCounter > 0) {
            alert('部分项目有错误，请查看表单中的提示信息');

            return false;
        }

        if(typeof(dao.type) == 'undefined') {
            alert('请选择会员类型');

            return false;
        }

        if(typeof(this.typeUrl[dao.type]) == 'undefined') {
            alert('会员类型有误');

            return false;
        }

        var progress = $.messager.progress, 
            url = this.typeUrl[dao.type] + '&a=doSave';

        progress({text : '正在保存数据，请稍等...'});

        $.post(url, dao, function(j){
            progress('close');
            $(window).trigger('User_edit_save', j);
        }, 'json');
    },

    checkQq : function($o) {
        var val = $o.val();

        try {
            if(val.length < 1) {
                throw new Error('请输入QQ号');
            }

            if(!isQq(val)) {
                throw new Error('QQ号有误');
            }
        } catch(e) {
            this.showErrorTips($o, e.message);

            return false;
        }

        this.removeTips($o);

        return true;
    },

    checkContact : function($o) {
        var val = $o.val();

        try {
            if(val.length < 1) {
                throw new Error('请输入联系人');
            }
        } catch(e) {
            this.showErrorTips($o, e.message);

            return false;
        }

        this.removeTips($o);

        return true;
    },

    checkPasswd : function($o) {
        var val = $o.val();

        try {
            if(val.length < 1) {
                throw new Error('请输入密码');
            }

            if(val.length < Conf.get('PASSWD_MIN_LEN') || val.length > Conf.get('PASSWD_MAX_LEN')) {
                throw new Error('密码长度必须在' + Conf.get('PASSWD_MIN_LEN') + '-' + Conf.get('PASSWD_MAX_LEN') + '之间');
            }
        } catch(e) {
            this.showErrorTips($o, e.message);

            return false;
        }

        this.removeTips($o);

        return true;
    },

    checkPasswdForModify : function($o) {
        var val = $o.val();

        try {
            if(val.length < 1) {
                return true;
            }

            if(val.length < Conf.get('PASSWD_MIN_LEN') || val.length > Conf.get('PASSWD_MAX_LEN')) {
                throw new Error('密码长度必须在' + Conf.get('PASSWD_MIN_LEN') + '-' + Conf.get('PASSWD_MAX_LEN') + '之间');
            }
        } catch(e) {
            this.showErrorTips($o, e.message);

            return false;
        }

        this.removeTips($o);

        return true;
    },

    checkName : function($o) {
        var val = $o.val(),
            that = this;

        try {
            if(val.length < 1) {
                throw new Error('请输入登陆名称');
            }

            if(val.length < Conf.get('USER_NAME_MIN_LEN') || val.length > Conf.get('USER_NAME_MAX_LEN')) {
                throw new Error('登陆名称长度必须在' + Conf.get('USER_NAME_MIN_LEN') + '-' + Conf.get('USER_NAME_MAX_LEN') + '之间');
            }

            $.getJSON('?c=User&a=checkExistsName', {user_name : val}, function(j){
                if(j.s) {
                    that.showErrorTips($o, j.m);
                }
            })
        } catch(e) {
            this.showErrorTips($o, e.message);

            return false;
        }

        this.removeTips($o);

        return true;
    },

    $getTips : function($prev) {
        var $tips = $prev.next('span');

        if($tips.length < 1) {
            $tips = $('<span></span>');
            $prev.after($tips);
        }

        return $tips;
    },

    showErrorTips : function($prev, msg) {
        var $o = this.$getTips($prev);
        $o.html(msg).addClass('formErrorTips');
    },

    removeTips : function($prev) {
        var $o = this.$getTips($prev);
        $o.remove();
    }

};

var Index = {
    init : function() {
        this.viewHalfHourFlow();

        setInterval(this.viewHalfHourFlow, 60000);
    },

    viewHalfHourFlow : function() {
        var url = '/click/Api/getPlanTypeFlowHalfHour.php',
            $o = $('#viewHalfHourFlow').find('span');

        $.getJSON(url, function(j){
            if(!j.s) {
                $o.html(j.m);

                return false;
            }

            var s = '';

            $.each(j.d, function(k, v){
                s += '<b>' + k.toUpperCase() + ':' + v + '</b>'
            })

            $o.html(s);
        })
    }
};


var ZnZone = {
    preview : function(param) {
        var url = 'index.php?c=Zone&a=preview',
            $out = $('#zn_zone-show-container'),
            width = parseInt(param.zone_width, 10),
            height = parseInt(param.zone_height, 10);

        if(isNaN(width) || width < 1) {
            alert('请输入正确的宽度');

            return false;
        }

        if(isNaN(height) || height < 1) {
            alert('请输入正确的高度');

            return false;
        }

        url += '&' + $.param(param);
        $out.height(height + 10);
        $out.attr('src', url);
    },

    save : function(param) {
        var url = '?c=Zone&a=doZnZoneSave';

        $.post(url, param, function(j){
            $(window).trigger('ZnZone_save', j);
        }, 'json');
    }, 

    /**
     * 显示供站长使用的广告代码
     * d = {zone_id : '广告位编号', width : '广告位宽度', height : '广告位高度'}
     */
    viewCode : function(d) {
        var jsCode = $('#zn_code-js-tpl').html(),
            htmlCode = $('#zn_code-html-tpl').html();

        jsCode = jsCode.replace(/{zone_id}/, d.zone_id);
        jsCode = jsCode.replace(/{width}/, d.width);
        jsCode = jsCode.replace(/{height}/, d.height);

        htmlCode = htmlCode.replace(/{zone_id}/, d.zone_id);
        htmlCode = htmlCode.replace(/{width}/, d.width);
        htmlCode = htmlCode.replace(/{height}/, d.height);

        $('#zn_zone-get-code__js__code').html(jsCode);
        $('#zn_zone-get-code__html__code').html(htmlCode);
    },

    /**
     * 获取表单中的数据
     */
    getFormValue : function($o) {
        var r = {},
            dao = Conf.get('formEditDao') || {};

        r.zone_name       = $o.find('[name=zone_name]').val() || dao.zone_name;
        r.zone_type       = $o.find('[name=zone_type]:checked').val() || dao.zone_type;
        r.zone_width      = parseInt($o.find('[name=zone_width]').val(), 10) || dao.zone_width;
        r.zone_height     = parseInt($o.find('[name=zone_height]').val(), 10) || dao.zone_height;
        r.zn_border_color = $o.find('[name=zn_border_color]').val() || dao.zn_border_color;
        r.zn_title_color  = $o.find('[name=zn_title_color]').val() || dao.zn_title_color;
        r.zn_bg_color     = $o.find('[name=zn_bg_color]').val() || dao.zn_bg_color;
        r.zone_pos_type   = $o.find('[name=zone_pos_type]:checked').val() || dao.zone_pos_type;

        var zoneId = parseInt($o.find('[name=zone_id]').val(), 10);

        if(zoneId) {
            r.zone_id = zoneId;
        }

        if(isNaN(r.zone_width) || r.zone_width < 1 || isNaN(r.zone_height) || r.zone_height < 1) {
            throw new Error('请输入正确的尺寸');
        }

        if(r.zone_type == 'zn_color_cloud') {
            r.color_style = $o.find('[name=color_style]:checked').val() || 0;
        }

        return r;
    },

    doSave : function ($formContainer) {
        try {
            var param = ZnZone.getFormValue($formContainer);
        } catch(e) {
            alert(e.message);

            return false;
        }

        $(window).one('ZnZone_save', function(e, j) {
            $(window).trigger('ZnZone_doSave', j);
        });

        ZnZone.save(param);
    }
};
